<?php
    class UsersController
    {
        private $model;
        private $view;
        
        public function __construct($model, $view) {
            $this->model = $model;
            $this->view  = $view;
            $view->setController($this);
        }
        
        // Parse the actions
        public function parseActions() {
            // See if there are actions to be taken:
            if(isset($_POST['save'])) {
                // Save the option:
                $name     = makeSafe($_POST['name']);
                $password = makeSafe($_POST['password']);
                $email    = makeSafe($_POST['email']);
                $action   = makeSafe($_POST['action']);                
                if(!empty($password)) {
                	$values = array('name'=>$name, 'password'=>md5($password), 'email'=>$email);
                } else {
                	$values = array('name'=>$name, 'email'=>$email);
                }
                if($action=='add') {
                    $this->model->addUser($values);
                } elseif($action=='edit') {
                    $id = $_POST['id'];
                    $this->model->updateUser($id, $values);
                }
            } elseif(isset($_POST['delete'])) {
                // Delete the option:
                $id = $_POST['id'];
                $this->model->deleteUser($id);
            }
        }
        
        // Render the view
        public function render() {
            // Show the interface:
            $this->view->showTop();
            if(isset($_POST['add'])) {
                $values = array('name'=>'', 'password'=>'', 'email'=>'', 'action'=>'add', 'id'=>0);
                $this->view->showForm($values);
            } elseif (isset($_POST['edit'])) {
                $id               = $_POST['id'];
                $values           = $this->model->getUser($id);
                $values['action'] = 'edit';
                $this->view->showForm($values);
            } else {                
                $records = $this->model->getRecords();
                if(count($records)==0) {
                    $this->view->showNoRecordsAvailable();    
                } else {
                    $this->view->showRecords($records);
                }
                $this->view->showAddEditDelete();
            }
            $this->view->showBottom();
        }        
    }
?>